package com.sinochem.yunlian.ship.common.filter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSONObject;
import com.sinochem.yunlian.ship.common.annotation.RequestCount;


/**
 * 统计接口访问次数
 */
@Component
@Aspect
public class RequestCountFilter{
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	
	@Before("@annotation(requestCount)")
	public void beforeExce( JoinPoint joinPoint, RequestCount requestCount) throws Throwable {
		
		log.info("输出注解信息:{}", requestCount);
		
		Object[] objects = null;
		
		HashMap<Object, Object> hashMap = new HashMap<>();
		// Redis key
		String key = requestCount.key();
		// 特定业务参数
		String parameter = requestCount.parameter();
		
		try {
			
			if (parameter != null && parameter.trim().length() > 0) {
				
				// 获取参数对象
				objects = joinPoint.getArgs();
				
				if (objects !=null  && objects.length > 0) {
					
					getParameterValue(objects, hashMap, parameter);
				}
			}
			
			log.info("参数信息:{}", hashMap);
			
			// 访问累计计数
			if( parameter != null && parameter.trim().length() > 0 ) {
				
				if (hashMap.containsKey(parameter)) {
					// 存在特定业务
					key= String.format(key,hashMap.get(parameter));
				}
			}
			log.info("输出最终的key值:{}", key);
			// 更新访问次数
			redisTemplate.opsForValue().increment(key, 1);
			
			log.info("输出{}访问次数:{}", key , redisTemplate.opsForValue().get(key));
			
		} catch (Exception e) {
			log.error("获取参数对象出错:{}", e);
		}
		
		log.info("输出参数:{}", objects);

	}


	/**
	 * 获取参数信息
	 * @param objects
	 * @param hashMap
	 * @param parameter 
	 */
	private void getParameterValue(Object[] objects, HashMap<Object, Object> hashMap, String parameter) {
		
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		
		log.info("请求方式:{}",request.getMethod());
		
		switch (request.getMethod()) {
		
		case "GET":
			
			log.info("请求方式:{},请求参数：{}",request.getMethod(), request.getParameter(parameter));
			// 目前仅支持一个请求参数
			if (request.getParameter(parameter) != null && request.getParameter(parameter).trim().length() > 0) {
				hashMap.put(parameter,request.getParameter(parameter));
			}
			break;
			
		case "POST":
			statisticalParameter(objects, hashMap);
			break;

		default:
			
			break;
		}
		
		
	}


	private void statisticalParameter(Object[] objects, HashMap<Object, Object> hashMap) {
		
		for (Object object : objects) {

			Map map = JSONObject.parseObject(JSONObject.toJSONString(object), Map.class);
			
			if (hashMap.isEmpty()) {
				// 首次初始化
				if (map != null && !map.isEmpty()) {
					hashMap.putAll(map);
				}
				
			} else {
				
				Iterator<Entry<Object, Object>> iterators =  map.entrySet().iterator();
				
				while (iterators.hasNext()) {
					
					Entry<Object, Object> entry = iterators.next();
					
					if (!hashMap.containsKey(entry.getKey())) {
						hashMap.put(entry.getKey(), entry.getValue());
					}
					
				}
			}
		}
	}

}
